package main.client;

import java.io.Serializable;
import java.util.ArrayList;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.*;


public class Project implements EntryPoint, Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * The message displayed to the user when the server cannot be reached or
	 * returns an error.
	 */
	private static final String SERVER_ERROR = "An error occurred while "
			+ "attempting to contact the server. Please check your network "
			+ "connection and try again.";

	/**
	 * Create a remote service proxy to talk to the server-side Greeting service.
	 */
	private final ServerSideAsync serverComm = GWT.create(ServerSide.class);
	
	private VerticalPanel wrapPanel = new VerticalPanel();
	private HorizontalPanel topPanel = new HorizontalPanel();
	private HorizontalPanel mainPanel = new HorizontalPanel();
	private VerticalPanel menuPanel = new VerticalPanel();
	private VerticalPanel userPanel = new VerticalPanel();
	private VerticalPanel cartPanel = new VerticalPanel();
	private VerticalPanel cartItemPanel = new VerticalPanel();
	private HorizontalPanel cartSumPanel = new HorizontalPanel();
	private Image mainLogo = new Image("images/main_logo.jpg");
	private Image audio_menu = new Image("images/audio_menu.jpg");
	private Image video_menu = new Image("images/video_menu.jpg");
	private Image accessories_menu = new Image("images/accessories_menu.jpg");
	private Image admin_menu = new Image("images/admin_menu.jpg");
	private final Label title = new Label("Online supermarket");
	private DecoratedStackPanel menu = new DecoratedStackPanel();
	private ArrayList<Item> items = new ArrayList<Item>();
	private User currentUser = new User();
	private FlexTable table = new FlexTable();
	private FlexTable cartTable = new FlexTable();
	private Label sumTotal = new Label();

	
	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {
	    AsyncCallback<String> callback = new AsyncCallback<String>() {
		      public void onFailure(Throwable caught) {}
		      public void onSuccess(String result) {}
		    };
		serverComm.hagf(callback);
		initMenu();
		initMain();
		mainLogo.setSize("90px", "90px");
		initUserPanel();
		setupCart();
		topPanel.add(mainLogo);
		topPanel.add(title);
		topPanel.add(userPanel);
		menuPanel.add(menu);
		
		Anchor home = new Anchor("Home");
		
		home.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				initMain();
			}
		});
		
		menuPanel.add(home);
		menuPanel.add(cartPanel);
		HorizontalPanel buttonPanel = new HorizontalPanel();
		
		Button checkout = new Button("Checkout cart");
		checkout.addClickHandler(new ClickHandler(){

			public void onClick(ClickEvent event) {
				initCheckoutPage();
			}});

		Button clearCart = new Button();
		clearCart.setText("Clear");
		
		clearCart.addClickHandler(new ClickHandler(){
			public void onClick(ClickEvent event) {
				AsyncCallback<String> callback = new AsyncCallback<String>() {
				      public void onFailure(Throwable caught) {
				    	  DecoratedPopupPanel simplePopup = new DecoratedPopupPanel(true);
				    	  simplePopup.add(new HTML("Fail " + caught.getMessage()));
				    	  simplePopup.show();
				      }
				      public void onSuccess(String result) {
				    	  initCart();
				    	  DecoratedPopupPanel simplePopup = new DecoratedPopupPanel(true);
				    	  simplePopup.add(new HTML("Success!"));
				    	  simplePopup.show();
				      }
				};
				serverComm.removeCart(callback);
			}
		});
		
		buttonPanel.add(checkout);
		buttonPanel.add(clearCart);
		
		buttonPanel.add(checkout);
		buttonPanel.add(clearCart);
		
		menuPanel.add(buttonPanel);	
		
		title.setStyleName("bigTitle");
		wrapPanel.addStyleName("wrapPanel");
		topPanel.addStyleName("topPanel");
		mainPanel.addStyleName("mainPanel");
		menuPanel.addStyleName("menuPanel");

		wrapPanel.add(topPanel);
		wrapPanel.add(mainPanel);
		RootPanel.get().add(wrapPanel);

	}
	/**
	 * A function for creating headers for the menu
	 * @param image
	 * @param text
	 * @return a HorizontalPanel with an image and a text to be used as a menu header
	 */
	private String createHeader(Image image, String text) {
		 	HorizontalPanel hPanel = new HorizontalPanel();
		    hPanel.setSpacing(0);
		    hPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
		    hPanel.add(image);
		    HTML headerText = new HTML(text);
		    hPanel.add(headerText);
		    return hPanel.getElement().getString();	
	}	
	/**
	 * A function for creating elements for the menu
	 * @param text
	 * @param click
	 * @return a HorizontalPanel with a link to be used in a menu
	 */
	private HorizontalPanel createMenuItem (String text, ClickHandler click) {
		HorizontalPanel hPanel = new HorizontalPanel();
		Anchor link = new Anchor(text);
		link.addClickHandler(click);
		hPanel.add(link);		
		return hPanel; 
	}
	/**
	 * A function that creates a list of menu items
	 * @param texts
	 * @param links
	 * @return a VerticalPanel with menu items
	 */
	private VerticalPanel createMenuItemList (ArrayList<String> texts, ArrayList<ClickHandler> links) {
		
		VerticalPanel vPanel = new VerticalPanel();
		for (int i = 0; i < texts.size(); i++) {
			HorizontalPanel hPanel = createMenuItem(texts.get(i), links.get(i));
			vPanel.add(hPanel);
		}
		return vPanel;
	}
	/**
	 * A function that creates the item page.
	 * Uses the item page creation function in Pages.java
	 * @param inItem
	 */
	private void initItemPage(Item inItem) {
		final Item item = inItem;
		final int id = item.getId();
		mainPanel.clear();
		mainPanel.add(menuPanel);
		mainPanel.add(new Pages().getItemPage(item, serverComm));
		ClickHandler addToCartHandler = new ClickHandler() {
			public void onClick(ClickEvent event) {
		          AsyncCallback<String> callback = new AsyncCallback<String>() {
				      public void onFailure(Throwable caught) {
				    	  DecoratedPopupPanel simplePopup = new DecoratedPopupPanel(true);
				    	  simplePopup.add(new HTML("Fail " + caught.getMessage()));
				    	  simplePopup.show();
				      }
				      public void onSuccess(String result) {
				    	  initCart();
				      }
		          };
		          Item sendItem = new Item();
		          sendItem.setId(id);
				 serverComm.addCartItem(sendItem, callback);
			}
		};
		Button addToCart = new Button("Add to cart");
		addToCart.addClickHandler(addToCartHandler);
		mainPanel.add(addToCart);
	}
	/**
	 * Creates the user registration page.
	 * Uses the registration page creation function in Pages.java
	 */
	private void initRegister() {
		mainPanel.clear();
		mainPanel.add(menuPanel);
		mainPanel.add(new Pages().getRegister(serverComm));		
	}
	/**
	 * Creates the user profile page.
	 * Uses the profile page creation function in Pages.java
	 */
	private void initProfile() {
		mainPanel.clear();
		mainPanel.add(menuPanel);
		mainPanel.add(new Pages().getProfile(serverComm));
	}
	/**
	 * Creates the main page.
	 * Uses the main page creation function in Pages.java
	 */
	private void initMain() {
		mainPanel.clear();
		mainPanel.add(menuPanel);
		mainPanel.add(new Pages().getMain(serverComm));
	}
	/**
	 * Creates the add item page.
	 * Uses the add item page creation function in Pages.java
	 */
	private void initAddItem() {
		mainPanel.clear();
		mainPanel.add(menuPanel);
		mainPanel.add(new Pages().getAddItem(serverComm));
	}
	/**
	 * Creates the remove item page.
	 * Uses the remove item page creation function in Pages.java
	 */
	private void initRemoveItem() {
		mainPanel.clear();
		mainPanel.add(menuPanel);
		mainPanel.add(new Pages().getRemoveItem(serverComm));
	}
	/**
	 * Creates the users page.
	 * Uses the users page creation function in Pages.java
	 */
	private void initUsers() {
		mainPanel.clear();
		mainPanel.add(menuPanel);
		mainPanel.add(new Pages().getUsers(serverComm));
	}
	/**
	 * Creates the carts page.
	 * Uses the carts page creation function in Pages.java
	 */
	private void initCarts() {
		mainPanel.clear();
		mainPanel.add(menuPanel);
		mainPanel.add(new Pages().getCarts(serverComm));
	}
	/**
	 * Creates the cart checkout page.
	 */
	private void initCheckoutPage() {
		mainPanel.clear();
		mainPanel.add(menuPanel);
		getCheckoutPage();
	}
	/**
	 * A function that draws the cart
	 */
	private void setupCart() {
		cartItemPanel.clear();
		cartPanel.clear();
		cartSumPanel.clear();
		table.clear();
		HorizontalPanel titlePanel = new HorizontalPanel();
		
		
		Label title = new Label("Your cart");
		title.setStyleName("mediumTitle");
		Label nameLabel = new Label("Name");
		Label priceLabel = new Label("Price");	
		priceLabel.setStyleName("floatRight");
		Label removeLabel = new Label("Remove");
		Label sumLabel = new Label("Total: ");
		removeLabel.setStyleName("floatRight");
		titlePanel.setStyleName("titlePanel");
		titlePanel.add(nameLabel);
		titlePanel.add(priceLabel);
		titlePanel.add(removeLabel);
		cartPanel.setStyleName("cartPanel");
		cartItemPanel.setStyleName("cartItemPanel");
		cartSumPanel.setStyleName("sumPanel");
		cartSumPanel.add(sumLabel);
		cartSumPanel.add(sumTotal);
		cartPanel.add(title);
		cartPanel.add(titlePanel);
		cartPanel.add(cartItemPanel);
		cartPanel.add(cartSumPanel);
		
	}
	/**
	 * A function that put items in the cart
	 */
	private void initCart() {
		AsyncCallback<ArrayList<Item>> callback = new AsyncCallback<ArrayList<Item>>() {
		      public void onFailure(Throwable caught) {
		    	  DecoratedPopupPanel simplePopup = new DecoratedPopupPanel(true);
		    	  simplePopup.add(new HTML("Fail " + caught.getMessage()));
		    	  simplePopup.show();
		      }

		      public void onSuccess(final ArrayList<Item> result) {
		    	  float totalPrice = 0;
		    	  if (result != null) {
	    			  table.clear();
		    		  for(int i = 0; i < result.size(); i++) {
		    			  final int index = new Integer(i);
		    			  totalPrice += result.get(i).getPrice()*result.get(i).getQuantity();
		    			  
		    			  Label name = new Label(result.get(i).getQuantity()+ "x " + result.get(i).getName());
		    			  Label price = new Label(new Float((result.get(i).getPrice())*result.get(i).getQuantity()).toString());
		    			  table.setWidget(i, 0, name);
		    			  table.setWidget(i, 1, price);
		    			  final Anchor link = new Anchor();
		    			  link.setText("X");
		    			  table.setWidget(i, 2, link);
		    			  link.setStyleName("floatRight");
		    			  link.setStyleName("red");
		    			  link.setTitle("Remove item from cart");
		    			  link.addClickHandler(new ClickHandler(){
							public void onClick(ClickEvent event) {
								AsyncCallback<String> callback = new AsyncCallback<String>() {
								      public void onFailure(Throwable caught) {
								    	  DecoratedPopupPanel simplePopup = new DecoratedPopupPanel(true);
								    	  simplePopup.add(new HTML("Fail " + caught.getMessage()));
								    	  simplePopup.show();
								      }

								      public void onSuccess(String result) {
								    		  initCart();
								    	  }
								    };
								 serverComm.removeCartItem(result.get(index).getId(), callback);
							}
		    			  });
		    			  table.setWidth("100%");
		    			  cartItemPanel.add(table);    		  
		    		  }
		    	  }
		    	  sumTotal.setText(new Float(totalPrice).toString());
		      }
		    };

		 serverComm.getCart(callback);
	}
	/**
	 * A function that creates the menu
	 */
	private void initMenu() {
		
		audio_menu.setWidth("32px");
		video_menu.setWidth("32px");
		accessories_menu.setWidth("32px");		
		admin_menu.setWidth("32px");
		
		
		final ArrayList<String> audioTextList = new ArrayList<String>();
		final ArrayList<String> videoTextList = new ArrayList<String>();
		final ArrayList<String> accTextList = new ArrayList<String>();
		final ArrayList<ClickHandler> audioLinkList = new ArrayList<ClickHandler>();
		final ArrayList<ClickHandler> videoLinkList = new ArrayList<ClickHandler>();
		final ArrayList<ClickHandler> accLinkList = new ArrayList<ClickHandler>();
			
		audioTextList.add("Speakers");
		audioTextList.add("Headphones");
		
		videoTextList.add("TV-sets");
		videoTextList.add("Monitors");
		
		accTextList.add("Cables");
		accTextList.add("Input devices");
		
		final ClickHandler clickAddItem = new ClickHandler() {
			public void onClick(ClickEvent event) {
				initAddItem();
			}
		};	
		final ClickHandler clickUsers = new ClickHandler() {
			public void onClick(ClickEvent event) {
				initUsers();
			}
		};	
		final ClickHandler clickCarts = new ClickHandler() {
			public void onClick(ClickEvent event) {
				initCarts();
			}
		};
		final ClickHandler clickRemoveItem = new ClickHandler() {
			public void onClick(ClickEvent event) {
				initRemoveItem();
			}
		};
		
		
		ClickHandler clickSpeakers = new ClickHandler() {
			public void onClick(ClickEvent event) {
				initItemsPage(1);	
			}
		};
		ClickHandler clickHeadphones = new ClickHandler() {
			public void onClick(ClickEvent event) {
				initItemsPage(2);	
			}
		};
		
		ClickHandler clickTV = new ClickHandler() {
			public void onClick(ClickEvent event) {
				initItemsPage(3);	
			}
		};
		ClickHandler clickMonitors = new ClickHandler() {
			public void onClick(ClickEvent event) {
				initItemsPage(4);	
			}
		};
		
		ClickHandler clickCables = new ClickHandler() {
			public void onClick(ClickEvent event) {
				initItemsPage(3);	
			}
		};
		ClickHandler clickInput = new ClickHandler() {
			public void onClick(ClickEvent event) {
				initItemsPage(4);	
			}
		};
		
		audioLinkList.add(clickSpeakers);
		audioLinkList.add(clickHeadphones);
		videoLinkList.add(clickTV);
		videoLinkList.add(clickMonitors);
		accLinkList.add(clickCables);
		accLinkList.add(clickInput);
		
		
		AsyncCallback<Integer> callback = new AsyncCallback<Integer>() {
		      public void onFailure(Throwable caught) {
		    	  DecoratedPopupPanel simplePopup = new DecoratedPopupPanel(true);
		    	  simplePopup.add(new HTML("Fail " + caught.getMessage()));
		    	  simplePopup.show();
		      }
		      public void onSuccess(Integer result) {
		    	  menu.clear();
		    		  if (result == 1) {
		    			  ArrayList<String> adminTextList = new ArrayList<String>();
		    			  ArrayList<ClickHandler> adminLinkList = new ArrayList<ClickHandler>();
		    			  adminTextList.add("Add item");
		    			  adminTextList.add("Users");
		    			  adminTextList.add("Bought stuff");
		    			  adminTextList.add("Remove item");		    			  
		    			  adminLinkList.add(clickAddItem);
		    			  adminLinkList.add(clickUsers);
		    			  adminLinkList.add(clickCarts);
		    			  adminLinkList.add(clickRemoveItem);

			    		  VerticalPanel menuItem4 = new VerticalPanel();
			    		  menuItem4 = createMenuItemList(adminTextList, adminLinkList);
			    			String menu4 = createHeader(admin_menu, "Admin");
			    			menu.add(menuItem4, menu4, true);
		    		  }
		    		  
		    		  VerticalPanel menuItem1 = new VerticalPanel();
		    		  VerticalPanel menuItem2 = new VerticalPanel();
		    		  VerticalPanel menuItem3 = new VerticalPanel();
		    		  
		    		  menuItem1 = createMenuItemList(audioTextList, audioLinkList);
		    		  menuItem2 = createMenuItemList(videoTextList, videoLinkList);
		    		  menuItem3 = createMenuItemList(accTextList, accLinkList);
		    		  
		    		  
		    					
		    			String menu1 = createHeader(audio_menu, "Audio");
		    			String menu2 = createHeader(video_menu, "Video");
		    			String menu3 = createHeader(accessories_menu, "Accessories");
		    			

		    			menu.add(menuItem1, menu1, true);
		    			menu.add(menuItem2, menu2, true);
		    			menu.add(menuItem3, menu3, true);
		    			menu.setWidth("100%");
		    		  
		    	  }
		    };
			 serverComm.checkAdmin(callback);

	}
	/**
	 * A function that creates the page for showing all items in a specific category
	 * @param category
	 */
	private void initItemsPage(int category) {
		mainPanel.clear();
		mainPanel.add(menuPanel);
		
		final FlexTable itemsTable = new FlexTable();
		itemsTable.setStyleName("table");
		Label nameButton = new Label("Name");
		Label boughtButton = new Label("Times Bought");
		Label priceButton = new Label("Price");

		itemsTable.setWidget(0,0, nameButton);
		itemsTable.setWidget(0,1, boughtButton);
		itemsTable.setWidget(0,2, priceButton);
		itemsTable.setWidget(0, 3, new Label("Description"));
		
		 AsyncCallback<ArrayList<Item>> callback = new AsyncCallback<ArrayList<Item>>() {
		      public void onFailure(Throwable caught) {
		    	  DecoratedPopupPanel simplePopup = new DecoratedPopupPanel(true);
		    	  simplePopup.add(new HTML("Fail " + caught.getMessage()));
		    	  simplePopup.show();
		      }

		      public void onSuccess(final ArrayList<Item> result) {
		    	  items.clear();
		    	  for (int i = 0; i < result.size(); i++) {
		    		  items.add(result.get(i));
		    	  }
		    	  for (int i = 0; i < result.size(); i++) {
		    		  final int temp = new Integer(i);
		    		  ClickHandler addToCartHandler = new ClickHandler() {

		    				public void onClick(ClickEvent event) {
		    			 		          
		    			          AsyncCallback<String> callback = new AsyncCallback<String>() {
		    					      public void onFailure(Throwable caught) {
		    					    	  DecoratedPopupPanel simplePopup = new DecoratedPopupPanel(true);
		    					    	  simplePopup.add(new HTML("Fail " + caught.getMessage()));
		    					    	  simplePopup.show();
		    					      }

		    					      public void onSuccess(String result) {
		    					    	  initCart();
		    					      }
		    			          };
		    					 serverComm.addCartItem(items.get(temp), callback);
		    					
		    				}
		    				
		    			};
		    		  Button addToCartButton = new Button("Add to cart");
		    		  addToCartButton.addClickHandler(addToCartHandler);
		    		  Item item = new Item();
		    		  item.copy(result.get(i));
		    		  Anchor itemLink = new Anchor(item.getName());
	    			  itemLink.setWidth("100%");
		    		  itemLink.addClickHandler(new ClickHandler() {

						public void onClick(ClickEvent event) {
							initItemPage(result.get(temp));							
						}
		    		  });
		    		  itemsTable.setWidget(i+1, 0, itemLink);
		    		  itemsTable.getWidget(i+1, 0).setStyleName("table");
		    		  itemsTable.getWidget(i+1, 0).setWidth("100%");
		    		  itemsTable.setWidget(i+1, 1, new Label(new Integer(item.getBought()).toString()));
		    		  itemsTable.getWidget(i+1, 1).setStyleName("table");
		    		  itemsTable.setWidget(i+1, 2, new Label(new Float(item.getPrice()).toString()));
		    		  itemsTable.getWidget(i+1, 2).setStyleName("table");
		    		  itemsTable.setWidget(i+1, 3, new Label(item.getDescription())); 
		    		  itemsTable.getWidget(i+1, 3).setStyleName("table");
		    		  itemsTable.setWidget(i+1, 4, addToCartButton);
		    	  }
		      }
		    };

		 serverComm.getAllItems(category, callback);
		
		 mainPanel.add(itemsTable);	
	}
	/**
	 * A function that signs in a user or returns an error message if the in data is wrong
	 * @param name
	 * @param pass
	 */
	private void login(String name, String pass) {
		
	    	  
		final User user = new User();
		AsyncCallback<User> callback = new AsyncCallback<User>() {
			public void onFailure(Throwable caught) {
				// TODO: Do something with errors.
			}
			
			public void onSuccess(User result) {
				if (result != null) {
					user.copy(result);
					initCart();
					initMenu();
					initMain();
					userPanel.clear();
					String temp = "Logged in as: " + result.getUserName();
					userPanel.add(new Label(temp));
					Anchor profile = new Anchor("Profile page");
					profile.addClickHandler(new ClickHandler(){
						public void onClick(ClickEvent event) {
							initProfile();						
						}
					});
					Anchor logout = new Anchor("Log out");
					logout.addClickHandler(new ClickHandler(){
						public void onClick(ClickEvent event) {	
							AsyncCallback<Integer> callback = new AsyncCallback<Integer>() {
								public void onFailure(Throwable caught) {
									// TODO: Do something with errors.
								}
								
								public void onSuccess(Integer result) {
									currentUser = new User();
									userPanel.clear();
									initUserPanel();
									initMenu();
									initMain();
									initCart();
								}	
							};
							serverComm.logout(callback);
						}
					});
					userPanel.add(profile);
					userPanel.add(logout);			
				}	
				else {
					DecoratedPopupPanel simplePopup = new DecoratedPopupPanel(true);
					simplePopup.add(new HTML("Incorrect username and/or password."));
					simplePopup.show();
				}
			}
		};
		serverComm.validateUser(name.toLowerCase(), pass, callback);		    		  
	}
	/**
	 * A function that creates the user panel
	 */
	private void initUserPanel() {

		userPanel.clear();
		
		AsyncCallback<User> callback = new AsyncCallback<User>() {
			public void onFailure(Throwable caught) {
				// TODO: Do something with errors.
			}
			
			public void onSuccess(User result) {
				if (result != null) {
					menu.clear();
					currentUser.copy(result);
					initCart();
					initMenu();
					initMain();
					userPanel.clear();
					String temp = "Logged in as: " + result.getUserName();
					userPanel.add(new Label(temp));
					Anchor profile = new Anchor("Profile page");
					profile.addClickHandler(new ClickHandler(){
						public void onClick(ClickEvent event) {
							initProfile();						
						}
					});
					Anchor logout = new Anchor("Log out");
					logout.addClickHandler(new ClickHandler(){
						public void onClick(ClickEvent event) {	
							AsyncCallback<Integer> callback = new AsyncCallback<Integer>() {
								public void onFailure(Throwable caught) {
									// TODO: Do something with errors.
								}
								
								public void onSuccess(Integer result) {
									currentUser = new User();
									initUserPanel();
									initMenu();
									initMain();
									initCart();
								}	
							};
							serverComm.logout(callback);
						}
					});
					userPanel.add(profile);
					userPanel.add(logout);	
			
			} else {
				Button registerButton = new Button("Register new user");
				registerButton.addClickHandler(new ClickHandler(){
					public void onClick(ClickEvent event) {
						    initRegister();			
					}			
				});
				
				Label nameLabel = new Label("Name:");
				Label passLabel = new Label("Password");
				final TextBox nameBox = new TextBox();
				final PasswordTextBox passBox = new PasswordTextBox();
				HorizontalPanel namePanel = new HorizontalPanel();
				HorizontalPanel passPanel = new HorizontalPanel();
				HorizontalPanel buttonPanel = new HorizontalPanel();
				
				passBox.addKeyPressHandler(new KeyPressHandler() {
					public void onKeyPress(KeyPressEvent event) {
						if (event.getCharCode() == KeyCodes.KEY_ENTER) {
					          login(nameBox.getText(), passBox.getText());
						}
					}
				});

				
				Button loginButton = new Button("Login");
				loginButton.addClickHandler(new ClickHandler(){
					public void onClick(ClickEvent event) {
						    login(nameBox.getText(), passBox.getText());		
					}			
				});
				
				namePanel.add(nameLabel);
				namePanel.add(nameBox);
				passPanel.add(passLabel);
				passPanel.add(passBox);
				buttonPanel.add(registerButton);
				buttonPanel.add(loginButton);
				namePanel.setStyleName("floatRight");
				passPanel.setStyleName("floatRight");
				
				
				userPanel.add(namePanel);
				userPanel.add(passPanel);
				userPanel.add(buttonPanel);
				userPanel.setStyleName("userPanel");
			}
			}
		};
		serverComm.getCurrentUser(callback);

		userPanel.setStyleName("userPanel");
		
		
		
	}
	/**
	 * Creates the checkout page
	 */
	public void getCheckoutPage() {
		cartTable.clear();
		VerticalPanel cartPanel = new VerticalPanel();
		 final Button buyButton = new Button("Buy");

		
		AsyncCallback<ArrayList<Item>> callback = new AsyncCallback<ArrayList<Item>>() {
		      public void onFailure(Throwable caught) {
		    	  DecoratedPopupPanel simplePopup = new DecoratedPopupPanel(true);
		    	  simplePopup.add(new HTML("Fail " + caught.getMessage()));
		    	  simplePopup.show();
		      }

		      public void onSuccess(final ArrayList<Item> result) {
		    	  if (result != null) {
		    		  float total = 0;
		    		  cartTable.setCellSpacing(0);
		    		  for(int i = 0; i < result.size(); i++) {	
		    			  
		    			  HorizontalPanel itemPanel = new HorizontalPanel();
		    			  itemPanel.setStyleName("cartTableRow");
		    			  itemPanel.setWidth("300px");
		    			  Label name = new Label(result.get(i).getQuantity() + "x " + result.get(i).getName());
		    			  Label price = new Label(new Float((result.get(i).getPrice())*result.get(i).getQuantity()).toString());
		    			  price.setWidth("100%");
		    			  price.setStyleName("alignRight");
		    			  itemPanel.add(name);
		    			  itemPanel.add(price);
		    			  cartTable.setWidget(i, 0, itemPanel);

		    			  
		    			  cartTable.setWidth("300px");
		    			  total += result.get(i).getQuantity()*result.get(i).getPrice();
		    		  }
		    		  
		    		  HorizontalPanel totalPanel = new HorizontalPanel();
		    		  totalPanel.setWidth("300px");
		    		  
		    		  int lastRow = cartTable.getRowCount();
		    		  Label totalPrice = new Label("Total:");
		    		  Label totalSum = new Label(new Float(total).toString());
		    		  totalSum.setWidth("100%");
	    			  totalSum.setStyleName("alignRight");
		    		  totalPrice.setStyleName("mediumTitle");
		    		  totalPanel.add(totalPrice);
		    		  totalPanel.add(totalSum);
		    		  cartTable.setWidget(lastRow, 0, totalPanel);
		    		  
		    		 
		    		  buyButton.addClickHandler(new ClickHandler() {

						public void onClick(ClickEvent event) {
							AsyncCallback<User> callback = new AsyncCallback<User>() {
			    				public void onFailure(Throwable caught) {
				        // 	TODO: Do something with errors.
			    				}
			    				public void onSuccess(User result) {
			    					
			    					if (result == null) {
			    						userData();
			    					} else {
			    						AsyncCallback<String> callback = new AsyncCallback<String>() {
						    				public void onFailure(Throwable caught) {
							        // 	TODO: Do something with errors.
						    				}
						    				public void onSuccess(String result) {
					    							showPopup();
						    					
						    						initCart();
						    						initMain();
						    					}
						    			};
						    			serverComm.buyItems(callback);
			    					}
			    				}
			    			};
			    			serverComm.getCurrentUser(callback);
							
						}
		    		  });
		    		  
		    		
		    	  }
		      }
		    };

		 serverComm.getCart(callback);

		cartPanel.add(cartTable);
		cartPanel.add(buyButton);
		mainPanel.add(cartPanel);
	}
	/**
	 * Creates a page where non-members submit their shipping info 
	 */
	public void userData() {
		mainPanel.clear();
		mainPanel.add(menuPanel);
		Label mainPanelTitle = new Label("Shipment information");
		Label fNameLabel = new Label("First name: ");
		final Label errorFName = new Label(" ");
		Label lNameLabel = new Label("Last name: ");
		final Label errorLName = new Label(" ");
		Label eMailLabel = new Label("E-mail: ");
		final Label errorEMail = new Label(" ");
		Label addressLabel = new Label("Address:");
		final Label errorAddress = new Label(" ");
		
		errorAddress.setStyleName("red");
		errorFName.setStyleName("red");
		errorLName.setStyleName("red");
		errorEMail.setStyleName("red");
		
		
		mainPanelTitle.setStyleName("mediumTitle");
		
		final TextBox fNameBox = new TextBox();
		final TextBox lNameBox = new TextBox();
		final TextBox eMailBox = new TextBox();
		final TextArea addressBox = new TextArea();
		
		fNameBox.setStyleName("floatRight");
		lNameBox.setStyleName("floatRight");
		eMailBox.setStyleName("floatRight");
		addressBox.setStyleName("floatRight");
		
		final User error = new User();
		error.setId(0);
		
		Button buyButton = new Button("Buy stuff");
		buyButton.addClickHandler(new ClickHandler(){
			public void onClick(ClickEvent event) {
				
				errorFName.setText(" ");
				errorLName.setText(" ");
				errorEMail.setText(" ");
				errorAddress.setText(" ");
				
				User user = new User();
				if (addressBox.getText().isEmpty()) {
					errorAddress.setText("You have to fill in an address");
					error.setId(1);
				}
				if (eMailBox.getText().isEmpty()){
					errorEMail.setText("You have to fill in an e-mail address");
					error.setId(1);
				}
				if (fNameBox.getText().isEmpty()) {
					errorFName.setText("You have to fill in a first name");
					error.setId(1);
				}
				if (lNameBox.getText().isEmpty()) {
					errorLName.setText("You have to fill in a last name");
					error.setId(1);
				}
				if (error.getId() == 0) {
					user.setAddress(addressBox.getText());
					user.seteMail(eMailBox.getText());
					user.setFirstName(fNameBox.getText());
					user.setLastName(lNameBox.getText());
					// Set up the callback object.
					AsyncCallback<String> callback = new AsyncCallback<String>() {
						public void onFailure(Throwable caught) {
							// TODO: Do something with errors.
						}
						public void onSuccess(String result) {
    						showPopup();
    					
    						initCart();
    						initMain();
						}
					};
					serverComm.buyItems(callback);
				}
				else {
					error.setId(0);
				}
			}
			
		});
		
		VerticalPanel inPanel = new VerticalPanel();
		VerticalPanel errorPanel = new VerticalPanel();
		HorizontalPanel namePanel = new HorizontalPanel();
		HorizontalPanel passPanel = new HorizontalPanel();
		HorizontalPanel fNamePanel = new HorizontalPanel();
		HorizontalPanel lNamePanel = new HorizontalPanel();
		HorizontalPanel eMailPanel = new HorizontalPanel();
		HorizontalPanel addressPanel = new HorizontalPanel();		
		
		fNamePanel.setWidth("300px");
		lNamePanel.setWidth("300px");
		passPanel.setWidth("300px");
		namePanel.setWidth("300px");
		eMailPanel.setWidth("300px");
		addressPanel.setWidth("300px");
		fNamePanel.setStyleName("floatRight");
		lNamePanel.setStyleName("floatRight");
		namePanel.setStyleName("floatRight");
		passPanel.setStyleName("floatRight");
		eMailPanel.setStyleName("floatRight");
		addressPanel.setStyleName("floatRight");
		
		fNamePanel.add(fNameLabel);
		fNamePanel.add(fNameBox);
		errorPanel.add(errorFName);
		lNamePanel.add(lNameLabel);
		lNamePanel.add(lNameBox);
		errorPanel.add(errorLName);
		eMailPanel.add(eMailLabel);
		eMailPanel.add(eMailBox);
		errorPanel.add(errorEMail);
		addressPanel.add(addressLabel);
		addressPanel.add(addressBox);
		errorPanel.add(errorAddress);
		inPanel.add(mainPanelTitle);
		inPanel.add(namePanel);
		inPanel.add(passPanel);
		inPanel.add(fNamePanel);
		inPanel.add(lNamePanel);
		inPanel.add(eMailPanel);
		inPanel.add(addressPanel);
		inPanel.add(buyButton);
		inPanel.setStyleName("floatLeft");
		inPanel.setSpacing(5);
		mainPanel.add(inPanel);
		mainPanel.add(errorPanel);
	}
	
	/**
	 * Shows a popup box with information about the successful purchase
	 */
	private void showPopup() {
		
		// Create the popup dialog box
		final DialogBox dialogBox = new DialogBox();
		dialogBox.setText("Purchase complete!");
		dialogBox.setAnimationEnabled(true);
		final Button closeButton = new Button("Close");
		VerticalPanel dialogVPanel = new VerticalPanel();
		dialogVPanel.addStyleName("dialogVPanel");
		dialogVPanel.add(new HTML("<b>Thank you for shopping in our online store.</b>"));
		dialogVPanel.add(new HTML("<br /><b>Your items will be sent within 12 weeks.</b>"));
		dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
		dialogVPanel.add(closeButton);
		dialogBox.setWidget(dialogVPanel);
		dialogBox.center();
		dialogBox.show();
		// Add a handler to close the DialogBox
		closeButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				dialogBox.hide();
			}
		});
		
	}
}